import React, { useState, useMemo, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Plus, 
  Network, 
  Settings,
  Lock,
  Unlock,
} from 'lucide-react';
import { DesignPattern, PatternCategory, SidebarProps } from '@/types';
import PatternCard from './PatternCard';

const categoryIcons = {
  creational: Plus,
  structural: Network,
  behavioral: Settings
};

const categoryLabels = {
  creational: '创建型模式',
  structural: '结构型模式', 
  behavioral: '行为型模式'
};


const Sidebar: React.FC<SidebarProps> = ({ 
  patterns, 
  selectedCategory, 
  onCategoryChange, 
  onPatternSelect, 
  currentPattern 
}) => {
  // 从localStorage读取展开状态，默认为false
  const [isExpanded, setIsExpanded] = useState(() => {
    const saved = localStorage.getItem('sidebar-expanded');
    return saved ? JSON.parse(saved) : false;
  });
  const [isHovered, setIsHovered] = useState(false);

  // 当展开状态改变时，保存到localStorage
  useEffect(() => {
    localStorage.setItem('sidebar-expanded', JSON.stringify(isExpanded));
  }, [isExpanded]);

  const groupedPatterns = useMemo(() => {
    const groups: Record<string, DesignPattern[]> = {
      creational: [],
      structural: [],
      behavioral: []
    };

    patterns.forEach(pattern => {
      groups[pattern.category].push(pattern);
    });

    return groups;
  }, [patterns]);

  const shouldShowContent = isExpanded || isHovered;

  return (
    <motion.aside 
      className={`${shouldShowContent ? 'w-80' : 'w-16'} bg-white/95 backdrop-blur-sm border-r border-gray-200 flex flex-col h-[calc(100vh-80px)] sticky top-20 transition-all duration-300`}
      initial={{ x: -300 }}
      animate={{ x: 0 }}
      transition={{ duration: 0.5 }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* Header */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-4">
          {shouldShowContent && (
            <h2 className="text-lg font-semibold text-gray-900">
              设计模式
            </h2>
          )}
          <motion.button
            onClick={() => setIsExpanded(!isExpanded)}
            className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            {isExpanded ? (
              <Lock className="w-5 h-5 text-gray-600" />
            ) : (
              <Unlock className="w-5 h-5 text-gray-600" />
            )}
          </motion.button>
        </div>
        
        {/* Category Filters */}
        {shouldShowContent && (
          <div className="grid grid-cols-3 gap-2">
            {Object.entries(categoryLabels).map(([key, label]) => {
              const Icon = categoryIcons[key as keyof typeof categoryIcons];
              const count = groupedPatterns[key]?.length || 0;
              const isActive = selectedCategory === key;
              
              return (
                <motion.button
                  key={key}
                  onClick={() => onCategoryChange(isActive ? 'all' : key as PatternCategory)}
                  className={`flex flex-col items-center p-3 rounded-lg text-center transition-all duration-200 ${
                    isActive 
                      ? 'bg-blue-100 text-blue-700 border-2 border-blue-300 shadow-sm' 
                      : 'hover:bg-gray-50 text-gray-700 border-2 border-transparent'
                  }`}
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                >
                  <Icon className="w-5 h-5 mb-1" />
                  <span className="text-xs font-medium leading-tight">
                    {label.replace('模式', '')}
                  </span>
                  <span className={`text-xs mt-1 px-2 py-0.5 rounded-full ${
                    isActive ? 'bg-blue-200 text-blue-800' : 'bg-gray-200 text-gray-600'
                  }`}>
                    {count}
                  </span>
                </motion.button>
              );
            })}
          </div>
        )}
      </div>

      {/* Patterns List */}
      {shouldShowContent && (
        <div className="flex-1 overflow-y-auto scrollbar-thin">
          <AnimatePresence mode="wait">
            {selectedCategory === 'all' || !selectedCategory ? (
              <motion.div
                key="all-patterns"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.3 }}
                className="p-3 space-y-4"
              >
                {Object.entries(groupedPatterns).map(([category, categoryPatterns]) => {
                  if (categoryPatterns.length === 0) return null;
                  
                  return (
                    <div key={category} className="space-y-2">
                      <div className="flex items-center space-x-2 text-xs font-medium text-gray-500 uppercase tracking-wide px-2 py-1">
                        <div className={`w-2 h-2 rounded-full ${
                          category === 'creational' ? 'bg-green-400' :
                          category === 'structural' ? 'bg-blue-400' : 'bg-purple-400'
                        }`}></div>
                        <span>{categoryLabels[category as keyof typeof categoryLabels]}</span>
                      </div>
                      
                      <div className="space-y-1">
                        {categoryPatterns.map((pattern) => (
                          <PatternCard
                            key={pattern.id}
                            pattern={pattern}
                            isActive={currentPattern?.id === pattern.id}
                            onClick={onPatternSelect}
                          />
                        ))}
                      </div>
                    </div>
                  );
                })}
              </motion.div>
            ) : (
              <motion.div
                key={`category-${selectedCategory}`}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 20 }}
                transition={{ duration: 0.3 }}
                className="p-3 space-y-1"
              >
                {groupedPatterns[selectedCategory]?.map((pattern) => (
                  <PatternCard
                    key={pattern.id}
                    pattern={pattern}
                    isActive={currentPattern?.id === pattern.id}
                    onClick={onPatternSelect}
                  />
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      )}

      {/* Footer */}
      {shouldShowContent && (
        <div className="p-3 border-t border-gray-200 bg-gray-50/50">
          <div className="text-xs text-gray-500 text-center">
            <p className="font-medium text-gray-600">23种经典设计模式</p>
            <p className="text-gray-400">GoF完整实现</p>
          </div>
        </div>
      )}
    </motion.aside>
  );
};

export default Sidebar;
